#include "unixtime.h"

const int UnixTime::_months_sum[12]= {0,31,59,90,120,151,181,212,243,273,304,334};

UnixTime::UnixTime(int utime):_utime(utime), _day(1), _month(1), _year(1970)
{
	const int sec_in_day = 3600*24;
	
	int remaining = utime/sec_in_day;
	if (utime < 0 && (utime%sec_in_day != 0)) {
		remaining -= 1 ;
	};
	
 	remaining += 134774;
 	_year = 1601;
 
	const int four_hundred_years_in_days = 400*365 + 100 - 4 + 1;
 	_year += 400*(remaining / four_hundred_years_in_days);
 	remaining %= four_hundred_years_in_days;
 
 	const int one_hundred_years_in_days = 100*365 + 25 - 1;
 	if (remaining == 4*one_hundred_years_in_days) {
 		_year += 399;
 		_month = 12;
 		_day = 31;
 		return;
 	};
 	_year += 100*(remaining/one_hundred_years_in_days);
 	remaining %= one_hundred_years_in_days;
 	
 	const int four_years_in_days = 4*365 + 1;
 	_year += 4*(remaining/four_years_in_days);
 	remaining %= four_years_in_days;
 	
 	const int one_year_in_days = 365;
 	if (remaining == 4*one_hundred_years_in_days) {
 		_year += 3;
 		_month = 12;
 		_day = 31;
 		return;
 	};
 	_year += (remaining/one_year_in_days);
 	remaining %= one_year_in_days;
 	
 	if (is_leap_year()) {
 		if (remaining == 31+28) {
			_month = 2;
			_day = 29;
			return;
 		}
 		else { 	
 			if (remaining > 31+28) remaining--;
 		}
 	};
 	for (_month = 0; remaining >= _months_sum[_month]; _month++ ) {};
 	remaining -= _months_sum[_month-1];
 	_day = remaining + 1;
};
